#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash bwa-0.7.17.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1
buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar environment-modules zlib-devel

wget  -t 0 -c -P $buildpath  https://github.com/lh3/bwa/archive/refs/tags/v0.7.17.tar.gz
tar xf $buildpath/v0.7.17.tar.gz -C $buildpath && rm -rf $buildpath/v0.7.17.tar.gz
basepath=$(cd $(dirname "${BASH_SOURCE[0]}") >/dev/null && pwd)
cd $buildpath/bwa-0.7.17
sed -i "s/gcc/clang/" Makefile
if `git clone https://ghproxy.com/https://github.com/DLTcollab/sse2neon.git`
then 
   echo "sse2neon下载成功!(国内github加速下载)"
   cp sse2neon/sse2neon.h .
elif `git clone https://github.com/DLTcollab/sse2neon.git`
then 
   echo "sse2neon下载成功!"
   cp sse2neon/sse2neon.h .
else
   cp $basepath/src/sse2neon.h .
fi
sed -i "29c #include \"sse2neon.h\"" ksw.c
sed -i 's/const uint8_t rle_auxtab/extern const uint8_t rle_auxtab/g' rle.h
make -j$(nproc)
mkdir -p $installpath/bwa-0.7.17 &&  cp  -r $buildpath/bwa-0.7.17/* $installpath/bwa-0.7.17/

cat>"$installpath/bwa-0.7.17/bwa_modulefiles"<<EOF
#%Module1.0
conflict pnetcdf
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set BWA \$pwd
prepend-path PATH \$BWA
EOF
rm -rf $buildpath/bwa-0.7.17 
